package com.qdsg.ysg.doctor.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Address;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.gyf.immersionbar.ImmersionBar;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.nurse.activity.AtyAddCallPerson;
import com.qdsg.ysg.doctor.service.WebSocketService;
import com.qdsg.ysg.doctor.ui.dialog.PoliceCallDialog;
import com.qdsg.ysg.doctor.ui.kotlin.AtyWelcome;
import com.qdsg.ysg.doctor.ui.widget.LoadingDailog;
import com.qdsg.ysg.doctor.util.DisplayUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.response.BaseResponse;
import com.rest.response.ContactFindVO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LocationUtils;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.NetworkUtil;
import jz.joyoung.robot.util.PreferencesHelper;

public abstract class BaseActivity extends AppCompatActivity {
    public ImageView btn_back;
    public boolean flag = false;
    protected Activity mContext;
    protected String TAG;
    public static final int LOCATION_CODE = 301;

    private LoadingDailog loadingDailog;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            //为了防止重复启动多个闪屏页面
            finish();
            return;
        }
        if (savedInstanceState != null) {
            int currentPID = android.os.Process.myPid() ;
            if (currentPID != savedInstanceState.getInt("PID")) {
                startActivity(AtyWelcome.class);
                finish();
            }
        }

        TAG = getClass().getSimpleName();
        mContext = this;

        doBeforeSetcontentView();
        setContentView(getLayoutResource());
        ButterKnife.bind(this);
        initBack();
        initData();
        initViews();
    }


    public void initBack() {
        btn_back = findViewById(R.id.btn_back);
        ImageView ivPoliceCall = findViewById(R.id.iv_police_call);
        if (btn_back != null) {
            btn_back.setOnClickListener(v -> finish());
        }
        if (ivPoliceCall != null) {
            ivPoliceCall.setOnClickListener(v -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
                    if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED ||
                            ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
                                    != PackageManager.PERMISSION_GRANTED) {
                        //请求权限
                        ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
                    } else {
                        showCallPersonDialog();

                    }
                } else {
                    showCallPersonDialog();
                }
            });
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("PID", android.os.Process.myPid());
    }

    /**
     * 设置layout前配置
     */
    private void doBeforeSetcontentView() {
        ImmersionBar.with(this).keyboardEnable(true).fitsSystemWindows(true).statusBarColor(R.color.white).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //我看可以重启服务，如果服务断了
        String token = PreferencesHelper.getInstance().getString(this, "token");
        if (!UtilString.isEmpty(RestClient.getInstance().token)) {
            checkServiceRunning(mContext);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 清除editText的焦点
     *
     * @param v   焦点所在View
     * @param ids 输入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏键盘
     *
     * @param v   焦点所在View
     * @param ids 输入框
     * @return true代表焦点在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText tmp_et = (EditText) v;
            for (int id : ids) {
                if (tmp_et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }


    //是否触摸在指定view上面,对某个控件过滤
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) {
            return false;
        }
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
//            return true;
//        }
//        lastClickTime = System.currentTimeMillis();
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(filterViewByIds(), ev)) {
                return super.dispatchTouchEvent(ev);
            }
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0) {
                return super.dispatchTouchEvent(ev);
            }
            View v = getCurrentFocus();
            if (isFocusEditText(v, hideSoftByEditViewIds())) {
                //隐藏键盘
//                KeyBoardUtils.hideInputForce(this);
                clearViewFocus(v, hideSoftByEditViewIds());
            }
        }
        return super.dispatchTouchEvent(ev);

    }


    /**
     * 传入EditText的Id
     * 没有传入的EditText不做处理
     *
     * @return id 数组
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }

    /**
     * 传入要过滤的View
     * 过滤之后点击将不会有隐藏软键盘的操作
     *
     * @return id 数组
     */
    public View[] filterViewByIds() {
        return null;
    }

    protected abstract int getLayoutResource();

    protected abstract void initData();

    protected abstract void initViews();


    /**
     * 防止闪屏加载框
     *
     * @param activity
     */
    public void showProgressDialog(Activity activity) {
        if (NetworkUtil.isNetworkAvailable(this)) {
            if (activity != null) {
                LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(this)
                        .setMessage("加载中...")
                        .setCancelable(true)
                        .setCancelOutside(false);
                loadingDailog = loadBuilder.create();
                loadingDailog.showDialog();
            }
        }
    }

    public void dismissProgressDialog() {
        if (loadingDailog != null) {
            loadingDailog.hideDialog();
        }
    }

    /**
     * 打开设置权限页面
     */
    @SuppressLint("ObsoleteSdkInt")
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void startNotificationSetting(Context context) {
        try {
            Intent mIntent = new Intent();
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else {
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                mIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
            context.startActivity(mIntent);

        } catch (Exception ignored) {

        }
    }

    // 检查服务重新连接
    public void checkServiceRunning(Context context) {
        if (!UtilString.isEmpty(RestClient.getInstance().token) && !UtilString.isEmpty(BaseApplication.currentUserId)) {
            if (!isServiceRunning(mContext, "com.qdsg.ysg.doctor.service.WebSocketService")) {
                Log.e("基类服务死了---", "妈的");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(new Intent(mContext, WebSocketService.class));
                } else {
                    startService(new Intent(mContext, WebSocketService.class));
                }
            } else {
                Log.e("基类服务还在---", "哈哈哈");
            }
        } else {
            stopService(new Intent(mContext, WebSocketService.class));
        }
    }

    // 服务是否运行
    public boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        assert am != null;
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) am.getRunningServices(Integer.MAX_VALUE);


        for (ActivityManager.RunningServiceInfo info : runningService) {// 获取运行服务再启动
            if (info.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == LOCATION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                try {
                    showCallPersonDialog();
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void showCallPersonDialog() {
        RestProxy.getInstance().findContact(new Observer<ContactFindVO>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(ContactFindVO contactFindVO) {

                if (UtilString.isEmpty(contactFindVO.data.contactName1) && UtilString.isEmpty(contactFindVO.data.contactName2) && UtilString.isEmpty(contactFindVO.data.contactName3)) {
                    startActivity(AtyAddCallPerson.class);
                } else {
                    LocationUtils.getInstance(mContext).setAddressCallback(new LocationUtils.AddressCallback() {
                        @Override
                        public void onGetAddress(Address address) {
                            String countryName = address.getCountryName();//国家
                            String adminArea = address.getAdminArea();//省
                            String locality = address.getLocality();//市
                            String subLocality = address.getSubLocality();//区
                            String featureName = address.getFeatureName();//具体地址
                            String subAdminArea = address.getSubAdminArea();//街道
//                String area = adminArea + locality + subLocality + subAdminArea + featureName;

                            PoliceCallDialog mPoliceCallDialog = PoliceCallDialog.newInstance(address);
                            mPoliceCallDialog.show(getSupportFragmentManager(), "PoliceCallDialog");
                            mPoliceCallDialog.setmListener((address1, appointmentAddress, name) -> {
                                Map<String, Object> map = new HashMap<>();
                                map.put("address", address1);
                                map.put("appointmentAddress", appointmentAddress);
                                map.put("name", name);
                                RestProxy.getInstance().oneKeyAlarm(map, new Observer<BaseResponse>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(BaseResponse baseResponse) {
                                        try {
                                            ToastUtil.showToastCenter(mContext, "报警成功");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        ToastUtil.onError(mContext, e);
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                            });
                        }

                        @Override
                        public void onGetLocation(double lat, double lng) {
                            LogUtil.e("定位经纬度", lat + "维度" + lng);
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        return DisplayUtil.getResources(this, resources, 1f);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(DisplayUtil.attachBaseContext(base, 1f));
    }
}